package persistencia;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.util.ArrayList;

import negocio.Area;
import negocio.Curso;

public class CursoDAO
{
	private static CursoDAO instancia;
	private final Connection c;
	
	private CursoDAO()
	{
		c = BDManager.getInstance().getConexion();
	}

	public static CursoDAO getInstance()
	{
		if(instancia ==null)
		{
			instancia = new CursoDAO();
		}
		return instancia;
	}
	
	public void guardar(Curso curso)
	{
		String query = "INSERT INTO curso( nombre, descripcion, area_fk, temario, sigla) VALUES ('" + curso.getNombre() + "','" + curso.getDescripcion() +"','" + curso.getArea().getId() + "','" + curso.getTemario() +"','"+ curso.getSigla()+"')";
		
		try {
			Statement s = c.createStatement();
			s.execute(query);
			s.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public ArrayList<Curso> getAll()
	{
		String query = "SELECT * FROM curso";
		Statement s;
		ResultSet rs;
		ArrayList<Curso> res = new ArrayList<Curso>();
		try {
			s = c.createStatement();
			rs = s.executeQuery(query);
			while(rs.next())
			{
				Area area= AreaDAO.getInstance().getArea(rs.getInt(4));
				res.add(new Curso(rs.getInt(1), rs.getString(2), rs.getString(3), area, rs.getString(5), rs.getString(6)));
			}
			s.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return res;
	}

	public Curso getCurso(int id) 
	{
		String query = "SELECT * FROM curso WHERE id=" + id;
		Statement s;
		ResultSet rs;
		Curso res = null;
		try{
			s = c.createStatement();
			rs = s.executeQuery(query);
			rs.next();
			Area area = AreaDAO.getInstance().getArea(rs.getInt(1));
			res = new Curso(rs.getInt(1), rs.getString(2), rs.getString(3), area, rs.getString(5), rs.getString(6));
		}
		catch(SQLException e)
		{
			e.printStackTrace();
		}
		return res;
	}
	
}
